import { computed, getCurrentInstance, onMounted, ref, shallowRef, watch } from 'vue'
import type { MenuProps, TableColumnType } from 'ant-design-vue'
import { ENUM_OPERATION_TYPE } from '@/utils/constant'

export function useBaseTable(props: any, emit: any) {
  const notification = useNotification()
  const popconfirm = usePopconfirm()
  console.log('4. 调用ts,输出props：', props)
  console.log('5. 调用ts,输出emit', emit)
  // 数据状态
  const state = {
    _columns: shallowRef<TableColumnType[]>(props.columns ?? []),
    _enableSelect: ref(props.enableSelect ?? true),
    _enableOnClick: ref(props.enableOnClick ?? true),
    _enableOnSelectAll: ref(props.enableOnSelectAll ?? true),
    _enableOnRowSelected: ref(props.enableOnRowSelected ?? true),
    _selectedRows: ref<any[]>([]),
    _selectedRowKeys: ref<any[]>([]),
    _selectedTreeKeys: ref<any[]>([]),
    _selectType: ref<string | null>('checkbox'),
    _pagination: ref({
      hideOnSinglePage: true,
      defaultCurrent: 1,
      current: 1,
      total: 0,
      defaultPageSize: 20,
      pageSize: 20,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['20', '50', '100', '200', '500', '1000'],
      showTotal: (total: number) => `共${total}条数据`,
    }),
    _rowSelection: ref({
      columnWidth: 50,
      onChange: () => { },
      onSelectAll: () => { },
      onSelect: () => { },
      type: 'checkbox',
      hideDefaultSelections: true,
    }),
    _checkAll: ref(true),
    _checkList: shallowRef<ComputedRef>(),
    _tableSize: ref<string[]>(['large']),
    _sizeItems: ref<MenuProps['items']>([
      {
        key: 'large',
        label: '默认',
        title: '默认',
      },
      {
        key: 'middle',
        label: '中等',
        title: '中等',
      },
      {
        key: 'small',
        label: '紧凑',
        title: '紧凑',
      },
    ]),
  }

  // 事件处理
  const handleAdd = () => emit('handleAdd')

  const handleDelete = (item: any) => {
    popconfirm.confirm({
      title: '确定要删除吗?',
      onOk: () => emit('handleDeleteSubmit', [item.id], [item]),
    })
  }
  const handleBatchDelete = () => {
    if (state._selectedRowKeys.value.length > 0) {
      popconfirm.confirm({
        title: '确定要删除吗?',
        onOk: () => emit('handleDeleteSubmit', state._selectedRowKeys.value, state._selectedRows.value),
      })
    }
    else {
      notification.warning({ message: '请选择至少一行数据', duration: 5 })
    }
  }
  const handleUpdate = (item: any) => emit('handleUpdate', item)
  const handleDetail = (item: any) => emit('handleDetail', item)
  const handleImport = () => emit('handleImport')
  const handleExport = () => emit('handleExport')
  const handleRowClick = (record: any, index: number, event: Event) => {
    if (state._enableOnClick.value)
      emit('handleRowClick', record, index, event)
  }
  const handleTableChange = (page: any) => {
    state._pagination.value.current = page.current
    state._pagination.value.pageSize = page.pageSize
    emit('loadData')
  }
  const handleSelectAll = (selected: boolean, selectedRows: any[]) => {
    if (state._enableOnSelectAll.value)
      emit('handleSelectAll', selected, selectedRows)
  }
  const handleRowSelected = (record: any, selected: boolean, selectedRows: any[]) => {
    if (state._enableOnRowSelected.value)
      emit('handleRowSelected', record, selected, selectedRows)
  }
  const handleRowSelectChange = (newSelectedRowKeys: any[], newSelectedRows: any[]) => {
    state._selectedRowKeys.value = newSelectedRowKeys
    state._selectedRows.value = newSelectedRows
  }
  const handleRefresh = (conditions: any) => {
    console.log('触发刷新')
    emit('loadData', conditions)
  }
  const handleCleanSelect = () => {
    state._selectedRowKeys.value = []
    state._selectedRows.value = []
  }

  // 计算属性 如果没有选择功能，清空 rowSelection
  const rowSelection = computed(() => {
    if (!props.enableSelect)
      return null

    return {
      columnWidth: 50,
      onChange: handleRowSelectChange,
      onSelectAll: state._enableOnSelectAll.value ? handleSelectAll : undefined,
      onSelect: state._enableOnRowSelected.value ? handleRowSelected : undefined,
      type: state._selectType.value,
      hideDefaultSelections: true,
    }
  })

  const handleCustomRow = (record: any, rowIndex: number) => {
    return {
      on: { // 事件
        // dblclick: this.onRowDoubleClick.bind(this, record, rowIndex),
        click: () => emit('handleRowClick'), // .bind(this, record, rowIndex),
        // contextmenu: (event) => { },
        // mouseenter: this.onMouseenter.bind(this, record, rowIndex),  // 鼠标移入行
        // mouseleave: this.onMouseleave.bind(this, record, rowIndex),  // 鼠标移出行
      },
    }
  }

  // #region 表格列头设定
  // 密度切换
  const handleSizeChange: MenuProps['onClick'] = (e) => {
    state._tableSize.value[0] = e.key as string
  }

  // 过滤
  function filterAction(value: string[]) {
    return state._columns.value.filter(item => value.includes(item.dataIndex))
  }

  const getCheckList = computed(() => state._columns.value.map(item => item.dataIndex))
  state._checkList = getCheckList.value
  // 备份columns
  const filterColumns = ref(filterAction(getCheckList.value))
  // 重置事件
  function handleResetChange() {
    state._checkList = getCheckList.value
    filterColumns.value = filterAction(getCheckList.value)
  }

  // checkbox点击事件
  function handleCheckChange(value: any) {
    const filterValue = filterAction(value)
    filterColumns.value = filterValue
  }

  const options = computed(() => {
    return state._columns.value.map((item) => {
      if (item.dataIndex === 'action') {
        return {
          label: item.title,
          value: item.dataIndex,
          disabled: true,
        }
      }
      return {
        label: item.title,
        value: item.dataIndex,
      }
    })
  })

  function handleCheckAllChange(e: any) {
    Object.assign(state, {
      checkList: e.target.checked ? getCheckList.value : [],
      indeterminate: true,
    })
    filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
  }

  watch(
    () => state._checkList,
    (val) => {
      state._indeterminate = !!val.length && val.length < getCheckList.value.length
      state._checkAll = val.length === getCheckList.value.length
    },
  )

  // #endregion

  // 暴漏跟baseTable.vue使用
  return {
    ...state,
    rowSelection,
    handleAdd,
    handleDelete,
    handleBatchDelete,
    handleUpdate,
    handleDetail,
    handleImport,
    handleExport,
    handleRefresh,
    handleTableChange,
    handleCustomRow,
    // 列头设置
    options,
    handleSizeChange,
    handleResetChange,
    handleCheckChange,
    handleCheckAllChange,
  }
}
